package edu.gduf.controller;

import edu.gduf.domain.LikeLog;
import edu.gduf.domain.ResultInfo;
import edu.gduf.domain.User;
import edu.gduf.service.UserService;
import edu.gduf.utils.JedisUtil;
import edu.gduf.utils.UserUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/user")
@SessionAttributes(value = {"uid","username","nickname","type","photo"},types = {Integer.class,String.class,String.class,Integer.class,
        String.class})
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JedisUtil jedisUtil;

    /**
     * 返回用户资料修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public String update(HttpServletRequest request){
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        User user = userService.findUserByUid(uid);
        // 根据用户身份返回响应的页面
        if(user.getType() == 1) {
            request.setAttribute("info", user);
            return "/user/updateinfo";
        }
        else if(user.getType() == 2) {
            user.setAssociation(userService.findAssociationByUid(user.getUid()));
            request.setAttribute("info",user);
            return "/user/updateassociationinfo";
        }
        return "404";
    }

    /**
     * 用户处理用户资料更新的表单
     * @param request
     * @param user
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public String update(HttpServletRequest request,User user){
        Integer uid =(Integer) request.getSession().getAttribute("uid");
        Integer type =(Integer) request.getSession().getAttribute("type");
        user.setUid(uid);
        user.setType(type);
        Integer res = userService.updateUser(user);
        request.setAttribute("nickname",userService.findNickNameByUid(uid));
        request.setAttribute("updatemsg","共有"+res+"条数据被修改");
        return "redirect:/user/update";

    }

    /**
     * 返回用户密码修改页面
     * @return
     */
    @RequestMapping(value = "/changepassword",method = RequestMethod.GET)
    public String changepassword(){
        return "/user/changepassword";
    }

    /**
     * 更改用户密码
     * @param request
     * @param oldpassword
     * @param password1
     * @param password2
     * @param model
     * @return
     */
    @RequestMapping(value = "/changepassword",method = RequestMethod.POST)
    public String changepassword(HttpServletRequest request,String oldpassword,String password1,String password2,Model model){
        if(!password1.equals(password2)){
            model.addAttribute("msg","请输入相同的密码");
        }else if (password1.length() < 6){
            model.addAttribute("msg","密码小于6位");
        } else {
            String username = (String) request.getSession().getAttribute("username");
            User user = userService.findUserByUserName(username);
            String dbpassword = user.getPassword();
            oldpassword = DigestUtils.md5DigestAsHex(oldpassword.getBytes());
            if(oldpassword.equals(dbpassword)){
                User user1 = new User();
                user1.setUsername(username);
                user1.setPassword(DigestUtils.md5DigestAsHex(password1.getBytes()));
                userService.updateUserAll(user1);
                model.addAttribute("msg","更改密码成功");
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
                return "login";
            }else {
                model.addAttribute("msg","旧密码错误!");
            }
        }
        return "/user/changepassword";
    }

    /**
     * 返回用户修改头像的页面
     * @return
     */
    @RequestMapping(value = "updatephoto",method = RequestMethod.GET)
    public String updatePhoto(){
        return "/user/face";
    }

    /**
     * 头像更新提交表单
     * @param model
     * @param picture
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadphoto",method = RequestMethod.POST)
    public String uploadphoto(HttpServletRequest request,Model model, @Param("picture") MultipartFile picture) {
        try {
            // 获取上传路径（由于tomcat项目部署后其他文件会被清空，这里设置项目外的路径并设置成虚拟路径
            String uploadPath = "F:\\project_xun\\upload\\images";
            File file = new File(uploadPath);
            if(!file.exists()){
                file.mkdir();
            }
            // 获取原始文件名称
            String filename = picture.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-","");
            // 构造唯一文件名
            filename = uuid + "_" + filename;
            // 将文件保存到服务器指定位置
            picture.transferTo(new File(uploadPath, filename));
            // 判断上传的是否为图片
            Image image = ImageIO.read(new File(uploadPath,filename));
            // 在数据库中更新用户头像
            User user = new User();
            Integer uid = (Integer)request.getSession().getAttribute("uid");
            user.setUid(uid);
            user.setPhoto("/upload/images/"+filename);
            userService.updatePhoto(user);
            request.setAttribute("msg","上传成功");
            model.addAttribute("photo","/upload/images/"+filename);
        }catch (IOException e){
            // 上传失败
            e.printStackTrace();
            request.setAttribute("msg","上传失败");
        }finally {
            return "redirect:/user/updatephoto";
        }
    }

    /**
     * 通过uid获取展示用户信息
     * @param uid
     * @return
     */
    @RequestMapping(value = "/{uid}",method = RequestMethod.GET)
    public String showUserInfo(@PathVariable("uid") String uid,HttpServletRequest request){
        try{
            Integer value = Integer.valueOf(uid);
            User user = userService.findUserByUid(value);
            if(user != null) {
                request.setAttribute("info", UserUtil.packUser(user));
                System.out.println(user);
                if(user.getType() == 1)
                    return "user/userinfo";
                else
                    return "user/associationinfo";
            }
        }catch (Exception e) {
            e.printStackTrace();
            return "404";
        }
        return "404";
    }

    /**
     * 查看用户登陆日志
     * @param request
     * @return
     */
    @RequestMapping(value = "/viewloginlog",method = RequestMethod.GET)
    public String showLoginLog(HttpServletRequest request){
        return "";
    }

    /**
     * 查看用户发布的信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/viewrelease",method = RequestMethod.GET)
    public String showRelease(HttpServletRequest request){
        return "user/showrelease";
    }

    /**
     * 对用户进行点赞
     * @param request
     * @param likeLog
     * @return
     */
    @RequestMapping(value = "/like",method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo likeUser(HttpServletRequest request, @RequestBody LikeLog likeLog) {
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        if(uid == null)
            return ResultInfo.failInfo("请先登陆");
        Integer like;
        if (likeLog.getLiked_uid() == uid)
            return ResultInfo.failInfo("不能对自己点赞");
        else if (jedisUtil.hasKey("liked::" + uid + "::" + likeLog.getLiked_uid()))
            return ResultInfo.failInfo("你在24小时内已经点过赞");
        else{
            like = userService.like(uid, likeLog.getLiked_uid());
            jedisUtil.set("liked::" + uid + "::" + likeLog.getLiked_uid(),"1");
            jedisUtil.expire("liked::" + uid + "::" + likeLog.getLiked_uid(),60*60*24);
        }
        if(like == 1)
            return ResultInfo.successInfo("点赞成功");
        else
            return ResultInfo.failInfo("点赞失败,未知原因");
    }

}
